<template>
    <div class="watermark-container">
        <div class="control-panel">
            <div class="upload-section">
                <n-upload :show-file-list="false" accept="image/*" @change="handleImageUpload" :max="1">
                    <n-button>选择图片</n-button>
                </n-upload>
            </div>
            <div class="watermark-options" v-if="imageUrl">
                <div class="text-input">
                    <span>水印文字:</span>
                    <n-input v-model:value="watermarkText" placeholder="请输入水印文字" class="text-field" />
                </div>
                <div class="style-options">
                    <n-space vertical>
                        <div class="option-item">
                            <span>字体大小:</span>
                            <n-input-number v-model:value="fontSize" :min="12" :max="72" />
                        </div>
                        <div class="option-item">
                            <span>透明度:</span>
                            <n-input-number v-model:value="opacity" :min="0" :max="100" :step="1"
                                class="number-input" />
                            <span class="unit">%</span>
                        </div>
                        <div class="option-item">
                            <span>旋转角度:</span>
                            <n-input-number v-model:value="rotation" :min="-90" :max="90" :step="1"
                                class="number-input" />
                            <span class="unit">°</span>
                        </div>
                        <div class="option-item">
                            <span>颜色:</span>
                            <n-color-picker v-model:value="textColor" />
                        </div>
                        <div class="option-item">
                            <span>位置:</span>
                            <n-select v-model:value="position" :options="positionOptions" class="position-select" />
                        </div>
                    </n-space>
                </div>
                <div class="action-buttons">
                    <n-button type="primary" @click="applyWatermark">
                        添加水印
                    </n-button>
                    <n-button @click="downloadImage" :disabled="!processedImageUrl">
                        下载
                    </n-button>
                </div>
            </div>
        </div>

        <div class="preview-panel" v-if="imageUrl">
            <div v-if="!imageUrl" class="empty-tip">
                请选择要添加水印的图片
            </div>
            <div v-else class="image-preview">
                <img :src="processedImageUrl || imageUrl" alt="Preview" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import view from '@renderer/util/ui/ViewUtil'

// 图片相关
const imageUrl = ref('')
const processedImageUrl = ref('')

// 水印选项
const watermarkText = ref('水印文字')
const fontSize = ref(24)
const opacity = ref(50)
const rotation = ref(-30)
const textColor = ref('#000000')

// 水印位置选项
const position = ref<'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | 'tile'>('tile')
const positionOptions = [
    { label: '左上角', value: 'topLeft' },
    { label: '右上角', value: 'topRight' },
    { label: '左下角', value: 'bottomLeft' },
    { label: '右下角', value: 'bottomRight' },
    { label: '铺满', value: 'tile' }
]

// 处理图片上传
const handleImageUpload = (data: { file: File, fileList: File[] }) => {
    const file = data.fileList[0]?.file || data.file?.file
    if (!file) {
        view.alertErrorMessage('请选择图片')
        return
    }

    const reader = new FileReader()
    reader.onload = (e) => {
        imageUrl.value = e.target?.result as string
        processedImageUrl.value = '' // 清空处理后的图片
    }
    reader.onerror = () => {
        view.alertErrorMessage('图片读取失败')
    }
    reader.readAsDataURL(file)
}

// 添加水印
const applyWatermark = () => {
    if (!imageUrl.value || !watermarkText.value) return

    const img = new Image()
    img.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        if (!ctx) return

        // 设置画布大小
        canvas.width = img.width
        canvas.height = img.height

        // 绘制原图
        ctx.drawImage(img, 0, 0)

        // 设置水印样式
        const alpha = opacity.value / 100  // 转换为0-1的透明度值
        ctx.fillStyle = textColor.value
        ctx.globalAlpha = alpha  // 使用全局透明度
        ctx.font = `${fontSize.value}px Arial`

        // 计算水印文字大小
        const metrics = ctx.measureText(watermarkText.value)
        const textWidth = metrics.width
        const textHeight = fontSize.value

        // 根据位置绘制水印
        if (position.value === 'tile') {
            // 保存当前状态
            ctx.save()

            // 设置旋转
            ctx.translate(canvas.width / 2, canvas.height / 2)
            ctx.rotate((rotation.value * Math.PI) / 180)
            ctx.translate(-canvas.width / 2, -canvas.height / 2)

            // 绘制平铺水印
            const gap = Math.max(textWidth, textHeight) * 2
            for (let y = 0; y < canvas.height; y += gap) {
                for (let x = 0; x < canvas.width; x += gap) {
                    ctx.fillText(watermarkText.value, x, y)
                }
            }

            // 恢复状态
            ctx.restore()
        } else {
            // 计算位置
            let x = 0
            let y = 0
            const padding = 20 // 边距

            switch (position.value) {
                case 'topLeft':
                    x = padding
                    y = textHeight + padding
                    break
                case 'topRight':
                    x = canvas.width - textWidth - padding
                    y = textHeight + padding
                    break
                case 'bottomLeft':
                    x = padding
                    y = canvas.height - padding
                    break
                case 'bottomRight':
                    x = canvas.width - textWidth - padding
                    y = canvas.height - padding
                    break
            }

            // 保存当前状态
            ctx.save()

            // 设置旋转（围绕水印中心点）
            ctx.translate(x + textWidth / 2, y - textHeight / 2)
            ctx.rotate((rotation.value * Math.PI) / 180)
            ctx.translate(-(x + textWidth / 2), -(y - textHeight / 2))

            // 绘制水印
            ctx.fillText(watermarkText.value, x, y)

            // 恢复状态
            ctx.restore()
        }

        // 恢复默认透明度
        ctx.globalAlpha = 1

        // 转换为图片URL
        processedImageUrl.value = canvas.toDataURL('image/png')
    }
    img.src = imageUrl.value
}

// 下载图片
const downloadImage = () => {
    if (!processedImageUrl.value) return

    const link = document.createElement('a')
    link.download = `watermarked-${Date.now()}.png`
    link.href = processedImageUrl.value
    link.click()
}

// 监听水印选项变化，自动更新水印
watch([position, watermarkText, fontSize, opacity, rotation, textColor], () => {
    if (imageUrl.value) {
        applyWatermark()
    }
})
</script>

<style scoped>
.watermark-container {
    height: 100%;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.control-panel {
    display: flex;
    gap: 16px;
    padding: 16px;
    border: 1px solid var(--border-color);
    border-radius: 4px;
}

.watermark-options {
    flex: 1;
    display: flex;
    gap: 16px;
}

.text-input {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 300px;
}

.text-field {
    flex: 1;
    min-width: 200px;
}

.style-options {
    flex: 1;
}

.option-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.option-item span {
    min-width: 80px;
}

.action-buttons {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.preview-panel {
    flex: 1;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
}

.empty-tip {
    color: var(--text-color-3);
}

.image-preview {
    max-width: 100%;
    max-height: 100%;
    overflow: auto;
    padding: 16px;
}

.image-preview img {
    max-width: 100%;
    height: auto;
    display: block;
}

.upload-section {
    min-width: 100px;
}

.position-select {
    width: 120px;
}

.number-input {
    width: 100px;
}

.unit {
    color: var(--text-color-3);
    margin-left: 4px;
}
</style>